package algorithms.que13;

import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

import java.util.Iterator;


public class QueueOfCircular<Item> implements Iterable<Item>
{
    private int N;
    private Node last;

    private class Node
    {
        Item item;
        Node next;
    }

    public boolean isEmpty()
    {return N==0;}

    public int size()
    {return N;}

    public void enqueue(Item item)
    {
        Node oldlast=last;
        last=new Node();
        last.item=item;
        last.next=oldlast.next;
        oldlast.next=last;
        N++;
    }

    public Item dequeue()
    {
        Item item=last.next.item;
        last.next=last.next.next;
        N--;
        if(isEmpty()) last=null;
        return item;
    }

    public Iterator<Item> iterator()  {return new ListIterator();}

    private class ListIterator implements Iterator<Item>
    {
        private Node current=last.next;
        public boolean hasNext(){return current!=last.next;}
        public void remove(){}
        public Item next()
        {
            Item item=current.item;
            current=current.next;
            return item;
        }//end next
    }//end class ListIterator
    public static void main(String[] args)
    {
        Queue<String> q=new Queue<String>();
        while(!StdIn.isEmpty())
        {
            String item=StdIn.readString();
            q.enqueue(item);
        }//end while
        for(String item:q)
            StdOut.println(item+" ");
    }//end main
}//end class